﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace R10App
{
    public struct SWFData
    {
        public double D1;
        public double D2;
    };

    class Waveform
    {
        private const int MaxSize = 300;
        Queue<SWFData> Data = new Queue<SWFData>();
        Bitmap offscreenSurf = new Bitmap(320, 220);
        private double ScalingX1 = 100.0;
        private double ScalingX2 = 100.0;
        private Color C1 = Color.Green;
        private Color C2 = Color.Blue;
        Font stringFont = new Font("Arial", 16);

        public void Init(double scaleMaxRange1, double scaleMaxRange2, Color c1, Color c2)
        {
            ScalingX1 = 100 / scaleMaxRange1;
            ScalingX2 = 100 / scaleMaxRange2;
            C1 = c1;
            C2 = c2;
        }

        public void AddPoints(SWFData[] data)
        {
            lock (this)
            {
                foreach (SWFData d in data)
                {
                    Data.Enqueue(d);
                    if (Data.Count > MaxSize) Data.Dequeue();
                }
            }
        }

        public void Draw(System.Windows.Forms.Panel panelWaveform)
        {
            Graphics g = Graphics.FromImage(offscreenSurf);
            g.Clear(Color.Black);

            if (Data.Count < 10) return;

            // crate points
            Point[] pts1;
            Point[] pts2;
            lock (this)
            {
                pts1 = new Point[Data.Count];
                pts2 = new Point[Data.Count];
                for (int i = 0; i != pts1.Length; i++)
                {
                    pts1[i] = new Point(i+10, (int)(110 - Data.ElementAt(i).D1 * ScalingX1));
                    pts2[i] = new Point(i + 10, (int)(110 - Data.ElementAt(i).D2 * ScalingX2));
                }
            }

            // draw lines
            g.DrawLines(Pens.Green, pts1);
            g.DrawLines(Pens.Blue, pts2);

            // draw axes
            g.DrawLine(Pens.White, 10, 10, 10, 210);
            g.DrawLine(Pens.White, 5, 10, 15, 10);
            g.DrawLine(Pens.White, 5, 210, 15, 210);
            g.DrawLine(Pens.White, 10, 110, 310, 110);
            

            // draw text
            g.DrawString(string.Format("{0}", 100 / ScalingX1), stringFont, Brushes.White, 15, 0);
            g.DrawString(string.Format("{0}", -100 / ScalingX1), stringFont, Brushes.White, 15, 195);

            // copy to image
            Graphics target = panelWaveform.CreateGraphics();
            target.DrawImage(offscreenSurf, 0, 0);
        }
    }
}
